import React, { Component, Fragment } from 'react';

import { Card, Button, Table, message, Space, Select, Input } from 'antd';
import { PlusOutlined } from '@ant-design/icons';

import { reqProduct, reqSearchProduct, reqUpdateProductStatus } from '../../../api';

import UpdateStatus from './UpdateStatus';
import LinkButton from '../../../components/LinkButton';

import memory from '../../../utils/memoryUtils';

const { Option } = Select;

export default class Home extends Component {

    state = {
        products: [],
        loading: true,
        pageNum: 1,
        pageSize: 10,
        total: 0,
        searcKeyword: '',
        searchType: 'productName',
    }

    columns = [
        {
            title: '商品名称',
            dataIndex: 'name',
            key: 'name',
            width: 200
        },
        {
            title: '商品描述',
            dataIndex: 'desc',
            key: 'desc',
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
            width: 100,
            render: price => '￥' + price
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            width: 100,
            render: (status, product) => (
                <UpdateStatus
                    status={status}
                    product={product}
                    updateProductStatus={(id, status) => this.updateProductStatus(id, status)}
                />
            )
        },
        {
            title: '操作',
            key: 'action',
            width: 100,
            render: (_, product) => (
                <Fragment>
                    <LinkButton onClick={() => this.toSubPage('/product/detail', product)}>
                        详情
                    </LinkButton>
                    <br />
                    <LinkButton onClick={() => this.toSubPage('/product/update', product)}
                    >修改</LinkButton>
                </Fragment>
            ),
        },
    ];

    toSubPage(url, product) {
        this.props.history.push(url, { product });
        memory.productPageState = this.state;
    }

    async getProduct(pageNum, pageSize) {

        if (memory.productPageState) {
            this.setState(memory.productPageState);
            memory.productPageState = null;
            return;
        }

        this.setState({ loading: true });
        const { searcKeyword, searchType } = this.state;
        let res = null;
        if (searcKeyword) {
            res = await reqSearchProduct({ pageNum, pageSize, keyword: searcKeyword, type: searchType });
        } else {
            res = await reqProduct(pageNum, pageSize);
        }

        if (res.status === 0) {
            const { data } = res;
            this.setState({
                products: data.list,
                loading: false,
                total: data.total,
                pageNum,
                pageSize
            })
        } else {
            message.error('获取商品数据失败！');
        }
    }

    async updateProductStatus(id, status) {
        const res = await reqUpdateProductStatus(id, status);
        if (res.status === 0) {
            message.success(status === 1 ? '商品上架成功！' : '商品下架成功！');
            const { pageNum, pageSize } = this.state;
            this.getProduct(pageNum, pageSize);
        } else {
            message.error('操作失败！');
        }
    }

    componentDidMount() {
        this.getProduct(1, this.state.pageSize);
    }

    render() {

        const { columns } = this;
        const { products, loading, pageNum, pageSize, total, searcKeyword, searchType } = this.state;

        return (
            <Card
                title={
                    <Space>
                        <Select
                            value={searchType}
                            onChange={searchType => this.setState({ searchType })}
                        >
                            <Option value="productName">按名称搜索</Option>
                            <Option value="productDesc">按描述搜索</Option>
                        </Select>
                        <Input
                            placeholder="关键字"
                            value={searcKeyword}
                            onChange={evt => this.setState({ searcKeyword: evt.target.value })}
                        />
                        <Button
                            type="primary"
                            onClick={() => this.getProduct(1, pageSize)}
                        >
                            搜索
                </Button>
                    </Space>
                }
                extra={<Button type="primary" onClick={() => this.toSubPage('/product/add')}><PlusOutlined />添加商品</Button>}
            >
                <Table
                    bordered
                    scroll={{ y: 450 }}
                    columns={columns}
                    loading={loading}
                    dataSource={products}
                    rowKey="_id"
                    pagination={{
                        showSizeChanger: true,
                        responsive: true,
                        showQuickJumper: true,
                        pageSize,
                        total,
                        defaultCurrent: 1,
                        current: pageNum,
                        onChange: (pageNum, pageSize) => this.getProduct(pageNum, pageSize),
                        onShowSizeChange: (pageNum, pageSize) => this.getProduct(pageNum, pageSize)
                    }}
                />
            </Card>
        )
    }
}
